using System;
using System.Collections.Generic;
using System.Text;
using THSLib;
using THSERP.BusinessEntities;
using THSERP.BaseProvider;
namespace THSERP.Modules.PurchaseOrder
{
    class PurchaseOrderEntities : ERPModuleEntities
    {
        #region Declare Constant
        public readonly static String strAPPurchaseOrderObjectName = "APPurchaseOrders";

        public readonly static String strAPPurchaseOrderItemsObjectName = "APPurchaseOrderItems";
        #endregion

        #region Declare all entities variables
        private APPurchaseOrdersInfo _aPPurchaseOrdersObject;
        private APPurchaseOrderItemsInfo _aPPurchaseOrderItemsObject;

        public THSItemsEntityList<PurchaseOrderItemsEntity> lstAPPurchaseOrderItems;
        #endregion

        #region Public Properties
        public APPurchaseOrdersInfo APPurchaseOrdersObject
        {
            get
            {
                return _aPPurchaseOrdersObject;
            }
            set
            {
                _aPPurchaseOrdersObject = value;
            }
        }
        public APPurchaseOrderItemsInfo APPurchaseOrderItemsObject
        {
            get
            {
                return _aPPurchaseOrderItemsObject;
            }
            set
            {
                _aPPurchaseOrderItemsObject = value;
            }
        }

        public THSItemsEntityList<PurchaseOrderItemsEntity> APPurchaseOrderItemsList
        {
            get
            {
                return lstAPPurchaseOrderItems;
            }
            set
            {
                lstAPPurchaseOrderItems = value;
            }
        }

        #endregion

        #region Constructor
        public PurchaseOrderEntities()
            : base()
        {
            _aPPurchaseOrdersObject = new APPurchaseOrdersInfo();

            _aPPurchaseOrderItemsObject = new APPurchaseOrderItemsInfo();

            lstAPPurchaseOrderItems = new THSItemsEntityList<PurchaseOrderItemsEntity>();
        }

        #endregion

        #region Init Main Object,Module Objects functions
        public override void InitMainObject()
        {

            MainObject = APPurchaseOrdersObject;
        }

        public override void InitModuleObjects()
        {
            ModuleObjects.Add("APPurchaseOrderItems", APPurchaseOrderItemsObject);
        }

        public override void InitModuleObjectList()
        {
            lstAPPurchaseOrderItems = new THSItemsEntityList<PurchaseOrderItemsEntity>();
            lstAPPurchaseOrderItems.InitTHSList(this, 
                                                 THSUtil.GetTableNameFromBusinessObjectType(typeof(APPurchaseOrdersInfo)),
                                                 THSUtil.GetTableNameFromBusinessObjectType(typeof(APPurchaseOrderItemsInfo)));
        }

        public override void InitGridControlInTHSList()
        {
            lstAPPurchaseOrderItems.InitTHSListGridControl();
        }

        public override void SetDefaultModuleObjectsList()
        {
            try
            {
                lstAPPurchaseOrderItems.SetDefaultListAndRefreshGridControl();

            }
            catch (Exception)
            {
                return;
            }
        }

        #endregion

        #region Invalidate Module Objects Functions
        public override void InvalidateModuleObjects(int iObjectID)
        {
            APPurchaseOrderItemsList.Invalidate(iObjectID);
        }
        #endregion

        #region Save Module Objects Functions
        public override void SaveModuleObjects()
        {
            if (Module != null)
            {
                if (Module.Toolbar.IsEditAction())
                {
                    THSItemsEntityList<PurchaseOrderItemsEntity> lstOldPurchaseOrderItemsEntity = new THSItemsEntityList<PurchaseOrderItemsEntity>();
                    lstOldPurchaseOrderItemsEntity.InitTHSList(this, 
                                                                THSUtil.GetTableNameFromBusinessObjectType(typeof(APPurchaseOrdersInfo)),
                                                                THSUtil.GetTableNameFromBusinessObjectType(typeof(APPurchaseOrderItemsInfo)));
                    lstOldPurchaseOrderItemsEntity.InvalidateAndNotUpdateModuleObjects(Module.Toolbar.CurrentObjectID);
                    lstOldPurchaseOrderItemsEntity.UpdateInventory(BusinessObject.DeletedAAStatus);
                }
            }


            APPurchaseOrderItemsList.SaveItemObjects(true);

            lstAPPurchaseOrderItems.UpdateInventory(BusinessObject.DefaultAAStatus);
        }
        #endregion

        public override void SetValuesAfterValidateProduct(int iICProductID)
        {
            //base.SetDefaultValueFromProduct(iICProductID);
            APPurchaseOrderItemsList.SetDefaultValuesFromProduct(iICProductID);
        }

        public override void CalculateTotalInformation(ref double dbTotalPrice, ref double dbTotalItemDiscountAmount, ref double dbDiscountAmount, ref double dbTotalTaxAmount, ref double dbTotalBuyingPrice, ref double dbTotalItemNetAmount, ref double dbTotalNetAmount, ref double dbTotalGrossAmount, ref double dbMarginPercent)
        {                       

            foreach (PurchaseOrderItemsEntity entPurchaseOrdersItem in APPurchaseOrderItemsList)
            {
                APPurchaseOrderItemsInfo objAPPurchaseOrderItemsInfo = (APPurchaseOrderItemsInfo)entPurchaseOrdersItem.SetToBusinessObject(strAPPurchaseOrderItemsObjectName);
                //Calculate item total price
                dbTotalPrice += THSUtil.Round(objAPPurchaseOrderItemsInfo.APPurchaseOrderItemPrice,THSApp.PriceDecimal);

                //Calculate total item discount amount
                dbTotalItemDiscountAmount += THSUtil.Round(objAPPurchaseOrderItemsInfo.APPurchaseOrderItemPrice * objAPPurchaseOrderItemsInfo.APPurchaseOrderItemProductDiscount / 100,THSApp.PriceDecimal);

                //Calculate total item tax amount
                dbTotalTaxAmount += THSUtil.Round(objAPPurchaseOrderItemsInfo.APPurchaseOrderItemPrice * objAPPurchaseOrderItemsInfo.APPurchaseOrderItemProductTaxPercent / 100,THSApp.PriceDecimal);

                //Calculate buying price
                int iICProductID = objAPPurchaseOrderItemsInfo.FK_ICProductID;
                ICProductsInfo objICProductsInfo = (ICProductsInfo)new ICProductsController().GetObjectByID(iICProductID);
                if (objICProductsInfo != null)
                {
                    dbTotalBuyingPrice += objICProductsInfo.ICProductSupplierPrice * entPurchaseOrdersItem.APPurchaseOrderItemProductQty;
                }
            }

            //Calculate dbTotalItemNetAmount(ZSum)
            dbTotalItemNetAmount = dbTotalPrice - dbTotalItemDiscountAmount;

            //Calculate dbSellOrderDiscountAmount
            APPurchaseOrdersInfo objAPPurchaseOrdersInfo = (APPurchaseOrdersInfo)MainObject;
            if (objAPPurchaseOrdersInfo.APPurchaseOrderIsDiscountPercentCheck)
                dbDiscountAmount = dbTotalItemNetAmount * objAPPurchaseOrdersInfo.APPurchaseOrderDiscountPerCent / 100;
            else
                dbDiscountAmount = objAPPurchaseOrdersInfo.APPurchaseOrderDiscountFix;

            //Calculate dbTotalNetAmount
            dbTotalNetAmount = dbTotalItemNetAmount - dbDiscountAmount;

            //Calculate Total Gross Amount
            dbTotalGrossAmount = dbTotalNetAmount + dbTotalTaxAmount;

            //Calculate Profit percent
            if (dbTotalPrice > 0)
                dbMarginPercent = (dbTotalItemNetAmount - dbTotalBuyingPrice) * 100 / dbTotalItemNetAmount;

        }

        public override void UpdateInventory(ERPModuleItemsEntity entItems, string strUpdateStatus)
        {
            

            String strMainTableName = THSUtil.GetTableNameFromBusinessObject(MainObject);
            String strItemTableName = strMainTableName.Substring(0, strMainTableName.Length - 1) + "Items";
            BusinessObject objItemsInfo = ((ERPModuleItemsEntity)entItems).SetToBusinessObject(strItemTableName);
            String strItemProductTypeColumnName = strItemTableName.Substring(0, strItemTableName.Length - 1) + "ProductType";
            String strItemProductType = THSDbUtil.GetPropertyValue(objItemsInfo, strItemProductTypeColumnName).ToString();

            //not update inventory if product is Service or Comment

            if (!strItemProductType.Contains(Product.ProductModule.cstProductTypeService) && !strItemProductType.Contains(Product.ProductModule.cstProductTypeComment))
            {
                int iICProductID = Convert.ToInt32(THSDbUtil.GetPropertyValue(objItemsInfo, "FK_ICProductID"));
                int iICStockID = Convert.ToInt32(THSDbUtil.GetPropertyValue(objItemsInfo, "FK_ICStockID"));
                int iICStockSlotID = Convert.ToInt32(THSDbUtil.GetPropertyValue(objItemsInfo, "FK_ICStockSlotID"));

                String strItemProductQtyColumnName = strItemTableName.Substring(0, strItemTableName.Length - 1) + "ProductQty";

                double dbItemProductQty = Convert.ToDouble(THSDbUtil.GetPropertyValue(objItemsInfo, strItemProductQtyColumnName));

                String strItemStatus = THSDbUtil.GetPropertyValue(objItemsInfo, "AAStatus").ToString();

                if (strUpdateStatus == BusinessObject.DefaultAAStatus)
                {
                    //Update Inventory Stock
                    if (strItemStatus == BusinessObject.DefaultAAStatus)
                    {
                        int iICInventoryStockID = TransactionUtil.UpdateInventoryStock(
                                                    iICProductID, iICStockID,
                                                    dbItemProductQty,
                                                    TransactionUtil.cstInventoryPurchaseOrder);

                        //Update Inventory Stock Slot
                        if (iICInventoryStockID > 0)
                        {
                            int iICInventoryStockSlotID = TransactionUtil.UpdateInventoryStockSlot(
                                                            iICInventoryStockID, iICProductID,
                                                            iICStockSlotID,
                                                            dbItemProductQty,
                                                            TransactionUtil.cstInventoryPurchaseOrder);
                        }
                    }
                }
                else if (strUpdateStatus == BusinessObject.DeletedAAStatus)
                {
                    //Update Inventory Stock
                    int iICInventoryStockID = TransactionUtil.UpdateInventoryStock(
                                                iICProductID, iICStockID,
                                                -dbItemProductQty,
                                                TransactionUtil.cstInventoryPurchaseOrder);

                    //Update Inventory Stock Slot
                    if (iICInventoryStockID > 0)
                    {
                        int iICInventoryStockSlotID = TransactionUtil.UpdateInventoryStockSlot(
                                                        iICInventoryStockID, iICProductID,
                                                        iICStockSlotID,
                                                        -dbItemProductQty,
                                                        TransactionUtil.cstInventoryPurchaseOrder);
                    }
                }

            }            
        }
    }
}
